package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.shiro.AdminAuthorizingRealm;
import com.qf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *
 * 管理员 认证对象
 * @author lixu
 *
 */
@RestController
@RequestMapping("/admin/auth")
@CrossOrigin
@Slf4j
public class AdminAuthController {
    @Resource
    DtsRoleService roleService;
    @Resource
    DtsPermissionService permissionService;

    @GetMapping("/captchaImage")
    public Object captchaImage() throws Exception{
        //1:验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2:uuid
        String uuid = UUID.randomUUID(true).toString();//true : UUID工具包

        //3:验证码图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(111,36,outputStream,code);
        //4: 验证码保存在Session中  UUID就是缓存的Key值
        CaptchaCodeManager.addToCache(uuid,code,null);//默认3分钟
        Map<String,Object> result = new HashMap<>();
        result.put("img", Base64.encode(outputStream.toByteArray()));
        result.put("uuid",uuid);
        return ResponseUtil.ok(result);
    }

    @PostMapping("/login")
    public Object login(@RequestBody String body){
        //通过JSON转换工具拿到传入的数据
        String code = JacksonUtil.parseString(body, "code");
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");
        String uuid = JacksonUtil.parseString(body, "uuid");

        String capthchaCode = CaptchaCodeManager.getCachedCaptcha(uuid);
           if(StringUtils.isEmpty(code)){
            log.error("【登录】发生错误：{}",AdminResponseCode.AUTH_CAPTCHA_EXPIRED.desc());
            //return ResponseUtil.fail(1,"验证码失效");//正式项目 硬编码问题
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }
        if(!code.equalsIgnoreCase(capthchaCode)){
            log.error("【登录】发生错误：{}",AdminResponseCode.AUTH_CAPTCHA_ERROR.desc());
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }

        Subject subject = SecurityUtils.getSubject();
        Md5Hash md5Hash = new Md5Hash(password,username,1024);
        try {
            subject.login(new UsernamePasswordToken(username,md5Hash.toString()));
        } catch (AuthenticationException e) {
            log.error("【登录】发生错误：{}",AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }
        Session session = subject.getSession();
        return ResponseUtil.ok(session.getId());
    }

    @GetMapping("/info")
    public Object info(){
        DtsAdmin dtsAdmin = (DtsAdmin) SecurityUtils.getSubject().getPrincipal();
        Set<String> roles = roleService.findByRoleIds(dtsAdmin.getRoleIds());
        Set<String> perms = permissionService.findByRoleIds(dtsAdmin.getRoleIds());
        Map<String,Object> result = new HashMap<>();
        result.put("roles",roles);
        result.put("name", dtsAdmin.getUsername());
        //result.put("perms","[\"*\"]");
        result.put("perms",perms);
        result.put("avatar",dtsAdmin.getAvatar());
        return ResponseUtil.ok(result);
    }


}
